package com.kye.express.business.invoice_online.detail;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.databinding.FragmentInvoiceDetailBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.invoice_online.GetInvoiceDetailResultBean;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 发票详情
 */
public class InvoiceDetailFragment extends BaseAppCompatFragment implements InvoiceDetailFragmentContract.InvoiceDetailFragmentView {
    private static final String ARG_DATA = "data";
    private FragmentInvoiceDetailBinding mBinding;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private InvoiceDetailListener mListener = null;
    private String mGroupCode = "";
    private Dialog mLoadingDialog;
    private InvoiceDetailFragmentContract.InvoiceDetailFragmentViewPresenter mPresendter;

    private double mTotalAmount = 0;
    private List<GetInvoiceDetailResultBean.SourceCodeDataBean> mSourceCodeDataBeans;
    private List<GetInvoiceDetailResultBean.WaybillNoDataBean> mWaybillNoDataBeans;

    public static InvoiceDetailFragment newInstance(String groupCode) {
        InvoiceDetailFragment fragment = new InvoiceDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_DATA, groupCode);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mListener = (context instanceof InvoiceDetailListener) ? (InvoiceDetailListener) context : null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_invoice_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = FragmentInvoiceDetailBinding.bind(view);
        mPresendter = new InvoiceDetailFragmentContract.InvoiceDetailFragmentViewPresenter(getActivity());
        mPresendter.bind(this);
        getActivity().setTitle(getString(R.string.invoice_detail));
        initView();
        initEvent();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresendter.unbind();
    }

    private void initView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mGroupCode = bundle.getString(ARG_DATA);
        }
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(GetInvoiceDetailResultBean.SourceCodeDataBean.class, new InvoiceDetailtemViewBinder(getActivity(), mListener));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        RecyclerViewDivider.with(getActivity())
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(getActivity(), 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mPresendter.getInvoiceDetail(mGroupCode);
    }

    private void initEvent() {
        RxView.clicks(mBinding.superTextWaybillCount)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mListener != null && mWaybillNoDataBeans != null && mWaybillNoDataBeans.size() >0) {
                            mListener.onOpenWaybillList(mWaybillNoDataBeans);
                        }
                    }
                });
    }

    @Override
    public void onComplete() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(GetInvoiceDetailResultBean datas) {
        if (datas != null) {
            double mTotalAmount = datas.getTotalAmount();
            mSourceCodeDataBeans = datas.getSourceCodeData();
            mWaybillNoDataBeans = datas.getWaybillNoData();
            mBinding.tvTotalPrice.setText("￥" + mTotalAmount);
            if (mSourceCodeDataBeans != null && mSourceCodeDataBeans.size() > 0){
                mDatas.clear();
                mDatas.addAll(mSourceCodeDataBeans);
                mAdapter.notifyDataSetChanged();
            }

            if (mWaybillNoDataBeans != null) {
                mBinding.superTextWaybillCount.setLeftTopString(String.format(getString(R.string.invoice_online_waybill_title), mWaybillNoDataBeans.size()));
                StringBuilder stringBuilder = new StringBuilder();
                for (GetInvoiceDetailResultBean.WaybillNoDataBean item : mWaybillNoDataBeans) {
                    stringBuilder.append(item.getWaybill()).append("、");
                }
                if (stringBuilder.length() > 0) {
                    String waybills = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
                    mBinding.superTextWaybillCount.setLeftBottomString(waybills);
                }
            }
        }
    }

    @Override
    public void onApiError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onOtherError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}
